// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod triple;
mod overlay;
pub mod toolchain;

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use toolchain::ToolchainsConfig;
pub use triple::TripleEnv;
pub use overlay::OverlayConfig;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct SystemConfig {
    pub default_toolchain: String,
    pub default_mirrors: Vec<String>,
    pub includes: Option<Vec<String>>,
    pub toolchains: ToolchainsConfig,
    pub mirrors: Option<MirrorsConfig>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct PreloadSystemConfig {
    pub includes: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MirrorsConfig(pub BTreeMap<String, String>);

#[derive(Debug, thiserror::Error)]
pub enum SystemConfigError {
    #[error("the default toolchain not found in config")]
    DefaultToolchainNotFound,
    #[error("the mirror '{0}' not found in config")]
    DefaultMirrorNotFound(String),
    #[error("the pkg name '{1}' in toolchain '{0}' is duplicated")]
    DuplicatedPkgName(String, String),
    #[error("the pkg name '{1}' in extra-dep-edges in toolchain '{0}' is not found")]
    EdgePkgnameNotFound(String, String),
}

impl SystemConfig {
    pub fn verify(&self) -> Result<(), SystemConfigError> {
        if !self.toolchains.0.contains_key(&self.default_toolchain) {
            return Err(SystemConfigError::DefaultToolchainNotFound);
        }
        self.toolchains.verify()?;
        for mirror_name in  self.default_mirrors.iter() {
            if self.mirrors.is_none() || !self.mirrors.as_ref().unwrap().0.contains_key(mirror_name) {
                return Err(SystemConfigError::DefaultMirrorNotFound(mirror_name.clone()));
            }
        }
        Ok(())
    }

    pub fn default_mirror_urls(&self) -> impl Iterator<Item = &String> {
        self.default_mirrors
            .iter()
            .map(|name| self.mirrors.as_ref().unwrap().0.get(name).unwrap())
    }
}
